import { Module } from 'vuex'
import type { TRootState } from '../type'
import type { TPlayMusic } from './type'
import { getMusicUrl, getMusicDetail } from '@/service/play-music'
import { judegPlayMusic } from '@/utils/play-rule'

const playMusicModule: Module<TPlayMusic, TRootState> = {
  namespaced: true,
  state() {
    return {
      musicId: 0, // 播放音乐Id
      musicUrl: '', // 播放音乐地址
      musicDetail: {}, // 播放音乐详情
      musicList: [], // 整个歌单的音乐id集合
      playIndex: 0, // 对应此时歌单播放歌曲的下标索引
      isPlay: false, // 音乐播放状态
      duration: 0 // 当前播放时段
    }
  },
  getters: {
    getMusicDetail(state) {
      if (state.musicDetail.al === undefined) {
        return {
          al: {
            picUrl:
              'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
            name: '歌名',
            pic: 0,
            id: 0
          },
          ar: [
            {
              id: 0,
              name: '歌手'
            }
          ],
          dt: 0
        }
      } else {
        return state.musicDetail
      }
    },
    getNowMusic(state) {
      return state.musicUrl
    },
    getIsPlay(state) {
      return state.isPlay
    },
    getDuration(state) {
      return state.duration
    }
  },
  mutations: {
    updateDuration(state, num: number) {
      state.duration = Number(num.toFixed(0))
    },
    updateMusicId(state, id: any) {
      state.musicId = id
    },
    updateMusicUrl(state, url: string) {
      state.musicUrl = url
    },
    updateMusicDetail(state, detail: any) {
      state.musicDetail = detail
    },
    updateMusicList(state, list: any) {
      state.musicList = list
    },
    updatePlayIndex(state, index: number) {
      state.playIndex = index
    },
    updateIsPlay(state, flag?: boolean) {
      if (flag != undefined) {
        state.isPlay = flag
      } else {
        state.isPlay = !state.isPlay
      }
    }
  },
  actions: {
    async playMusic({ commit, state }, row: any) {
      // 单曲状态清除歌单列表和下标
      if (row.singel) {
        commit('updateMusicList', [])
        commit('updatePlayIndex', 0)
      }
      // 判断能否切换歌曲
      if (!judegPlayMusic(row.playType, state)) {
        return false
      }
      if (row.playType == 'next') {
        row.index = state.playIndex + 1
        row.id = state.musicList[row.index].id
      } else if (row.playType == 'pre') {
        row.index = state.playIndex - 1
        row.id = state.musicList[row.index].id
      }
      // 普遍播放状态 row.index就是对应表格中的下标
      commit('updatePlayIndex', row.index)
      commit('updateMusicId', row.id)
      const urlData: any = await getMusicUrl(row.id)
      commit('updateMusicUrl', urlData.data[0].url)
      const detailData: any = await getMusicDetail(row.id)
      commit('updateMusicDetail', detailData.songs[0])
      commit('updateIsPlay', true)
    }
  }
}
export default playMusicModule
